package com.jdrx.sw.sewage.service.common;

import com.jdrx.platform.commons.rest.exception.BizException;
import com.jdrx.sw.sewage.beans.entity.SequenceDefinePO;
import com.jdrx.sw.sewage.dao.SequenceDefineDAO;
import com.jdrx.sw.sewage.service.base.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

@Service
public class SequenceDefineServiceImpl extends BaseServiceImpl {

    @Value("${spring.application.name}")
    private String platformCode;

    @Autowired
    private SequenceDefineDAO sequenceDefineDao;

    public long get(String key, String dataNode) throws BizException {
        SequenceDefinePO seq = this.sequenceDefineDao.findByKey(key, this.platformCode, dataNode);
        return (Long) Optional.ofNullable(seq.getVal()).orElse(0L);
    }

    @Transactional(rollbackFor = Exception.class)
    public long increment(String key, String dataNode) throws BizException {
        SequenceDefinePO seq = this.sequenceDefineDao.findByKey(key, this.platformCode, dataNode);
        long val = (Long) Optional.ofNullable(seq.getVal()).orElse(0L);
        return this.sequenceDefineDao.update(seq.getId(), val + 1L, new Date(), seq.getRemarks(), dataNode) > 0 ? val : 0L;
    }
}